package com.example.controller;

import com.example.pojo.Book;
import com.example.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@Controller
@RequestMapping("/api/Book")
public class BookController {

    @Autowired
    private BookService bookService;

    // 1. 查询所有图书
    @ResponseBody
    @GetMapping("/all")
    public ResponseEntity<List<Book>> getAllBooks() {
        // 调用 service 层获取所有书籍数据
        List<Book> books = bookService.getAllBooks();

        // 如果 books 为 null 或空，可以返回一个 204 No Content 状态码
        if (books == null || books.isEmpty()) {
            return ResponseEntity.noContent().build();
        }

        // 返回 200 OK 状态码并将数据封装在 ResponseEntity 中
        return ResponseEntity
                .ok()
                .contentType(MediaType.valueOf("application/json;charset=UTF-8"))
                .body(books);
    }

    // 2. 修改图书价格：传入id和newPrice
    @PutMapping("/updatePrice")
    public ResponseEntity<Map<String, Object>> updatePrice(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        boolean success = bookService.updatePrice(book.getId(), book.getPrice());
        result.put("success", success);
        result.put("message", success ? "状态更新成功" : "状态更新失败");
        return ResponseEntity.ok(result);
    }

    // 3. 修改图书状态：传入id和newStatus（0 上架 / 1 下架）
    @PutMapping("/updateStatus")
    public ResponseEntity<Map<String, Object>> updateStatus(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        boolean success = bookService.updateStatus(book.getId(), book.getStatus());
        result.put("success", success);
        result.put("message", success ? "状态更新成功" : "状态更新失败");
        return ResponseEntity.ok(result);
    }
}